<template>
  <div class="project-list-container">
    <el-card class="project-card" shadow="hover">
      <div class="header">
        <div class="title-section">
          <h2 class="page-title">
            <el-icon class="title-icon"><Folder /></el-icon>
            项目列表
            <el-tag v-if="!isAdmin" type="info" size="small" style="margin-left: 10px;">
              仅查看分配项目
            </el-tag>
          </h2>
          <p class="description">
            {{ isAdmin ? '管理系统项目，包括项目信息、状态和负责人' : '查看分配给您的项目信息' }}
            <span v-if="!isAdmin" style="color: #e6a23c; font-weight: 500;">
              (当前用户: {{ currentUser.Username }})
            </span>
          </p>
        </div>
        <el-button v-if="isAdmin" type="primary" @click="openDialog()" class="create-btn">
          <el-icon><Plus /></el-icon>
          新建项目
        </el-button>
      </div>

      <!-- 搜索和筛选区域 -->
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索项目名称、编号或项目经理..."
          class="search-input"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="filterState" placeholder="项目状态" clearable @change="handleSearch">
          <el-option label="进行中" value="进行中" />
          <el-option label="已完成" value="已完成" />
          <el-option label="暂停" value="暂停" />
          <el-option label="计划中" value="计划中" />
        </el-select>
      </div>

      <!-- 项目表格 -->
      <el-table
        :data="filteredProjectList"
        stripe
        border
        class="project-table"
        v-loading="loading"
        empty-text="暂无项目数据"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column prop="project_id" label="项目编号" min-width="120" />
        <el-table-column prop="project_name" label="项目名称" min-width="150">
          <template #default="scope">
            <div class="project-info">
              <el-icon class="project-icon"><Folder /></el-icon>
              <span class="project-name clickable" @click="goToProjectInfo(scope.row)">
                {{ scope.row.project_name }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="project_location" label="项目地点" min-width="120" />
        <el-table-column prop="project_manager" label="项目经理" min-width="120">
          <template #default="scope">
            {{ getUserNameById(scope.row.project_manager) }}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="项目状态" width="100">
          <template #default="scope">
            <el-tag :type="getStateTagType(scope.row.state)" size="small">
              {{ scope.row.state }}
            </el-tag>
          </template>

        </el-table-column>
        <el-table-column prop="project_type" label="项目类型" min-width="120" />
        <el-table-column prop="total_hours" label="项目总工时" min-width="120" />
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right" v-if="isAdmin">
          <template #default="scope">
            <el-button size="small" type="primary" @click="openDialog(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 项目创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '编辑项目' : '新建项目'"
      width="700px"
      align-center
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目编号" prop="project_id">
              <el-input v-model="form.project_id" placeholder="请输入项目编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="project_name">
              <el-input v-model="form.project_name" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目地点" prop="project_location">
              <el-input v-model="form.project_location" placeholder="请输入项目地点" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目经理" prop="project_manager">
              <el-select v-model="form.project_manager" placeholder="请选择项目经理" style="width: 100%">
                <el-option
                  v-for="user in userList"
                  :key="user.id"
                  :label="user.Username"
                  :value="user.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目状态" prop="state">
              <el-select v-model="form.state" placeholder="请选择项目状态" style="width: 100%">
                <el-option label="计划中" value="计划中" />
                <el-option label="进行中" value="进行中" />
                <el-option label="已完成" value="已完成" />
                <el-option label="暂停" value="暂停" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目总工时" prop="total_hours">
              <el-input v-model="form.total_hours" placeholder="请输入项目总工时" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目类型" prop="project_type">
              <el-select v-model="form.project_type" placeholder="项目类型" style="width: 100%">
                <el-option label="软件项目" value="软件项目" />
                <el-option label="硬件项目" value="硬件项目" />
                <el-option label="工程项目" value="工程项目" />
                <el-option label="其他项目" value="其他项目" /> 
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="项目备注信息（选填）" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Folder, Plus, Search, Edit, Delete } from '@element-plus/icons-vue'
import { getProjectList, createProject, updateProject, deleteProject } from '../../api/project'
import { getUserList } from '../../api/user'
import { getUserProjectList, createUserProject, updateUserProject, deleteUserProject } from '../../api/userProject'

const projectList = ref([])
const userList = ref([])
const userProjectList = ref([])
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const searchKeyword = ref('')
const filterState = ref('')
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const formRef = ref()
const router = useRouter()

// 获取当前登录用户信息
const currentUser = ref(JSON.parse(localStorage.getItem('user') || '{}'))
const isAdmin = computed(() => currentUser.value.userType === '管理员')

// 保存原始项目经理ID，用于编辑时比较
const originalProjectManager = ref('')

const form = ref({
  id: null,
  project_id: '',
  project_name: '',
  project_location: '',
  project_manager: '',
  state: '计划中',
  total_hours: '',
  remark: ''
})

const formRules = {
  project_id: [{ required: true, message: '请输入项目编号', trigger: 'blur' }],
  project_name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  project_location: [{ required: true, message: '请输入项目地点', trigger: 'blur' }],
  project_manager: [{ required: true, message: '请选择项目经理', trigger: 'change' }],
  total_hours: [{ required: true, message: '请输入项目总工时', trigger: 'blur' }],
  state: [{ required: true, message: '请选择项目状态', trigger: 'change' }]
}

// 获取状态标签类型
function getStateTagType(state) {
  const stateMap = {
    '计划中': 'info',
    '进行中': 'primary',
    '已完成': 'success',
    '暂停': 'warning'
  }
  return stateMap[state] || 'info'
}

// 生成32位GUID
function generateGUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0
    const v = c === 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  }).replace(/-/g, '')
}

// 根据ID获取用户名
function getUserNameById(id) {
  const user = userList.value.find(u => u.id === id)
  return user ? user.Username : id
}

// 过滤后的项目列表（根据权限过滤）
const filteredProjectList = computed(() => {
  let filtered = projectList.value
  
  // 如果不是管理员，只显示分配给当前用户的项目
  if (!isAdmin.value) {
    const userProjectIds = userProjectList.value
      .filter(relation => relation.Userid === currentUser.value.id)
      .map(relation => relation.Porojectid)
    
    filtered = filtered.filter(project => userProjectIds.includes(project.project_id))
  }
  
  // 搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(project => 
      project.project_name.toLowerCase().includes(keyword) ||
      project.project_id.toLowerCase().includes(keyword) ||
      getUserNameById(project.project_manager).toLowerCase().includes(keyword)
    )
  }
  
  // 状态过滤
  if (filterState.value) {
    filtered = filtered.filter(project => project.state === filterState.value)
  }
  
  // 更新总数
  total.value = filtered.length
  
  // 前端分页处理
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

// 打开对话框
function openDialog(project = null) {
  if (project) {
    form.value = { ...project }
    originalProjectManager.value = project.project_manager // 保存原始项目经理ID
  } else {
    form.value = {
      id: null,
      project_id: '',
      project_name: '',
      project_location: '',
      project_manager: '',
      state: '计划中',
      remark: ''
    }
    originalProjectManager.value = ''
  }
  dialogVisible.value = true
}

// 加载用户列表
async function loadUsers() {
  try {
    const params = { page: 1, pageSize: 1000 }
    const res = await getUserList(params)
    userList.value = res.records || []
  } catch (error) {
    console.error('加载用户列表失败:', error)
  }
}

// 加载用户项目关联列表
async function loadUserProjects() {
  try {
    const params = { page: 1, pageSize: 1000 }
    const res = await getUserProjectList(params)
    userProjectList.value = res.records || []
  } catch (error) {
    console.error('加载用户项目关联失败:', error)
  }
}

// 加载项目列表
async function loadProjects() {
  loading.value = true
  try {
    const params = {
      page:1,
      pageSize: 1000
    }
    const res = await getProjectList(params)
    projectList.value = res.records || []
  
  } catch (error) {
    ElMessage.error('加载项目列表失败')
    console.error('加载项目列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索处理
function handleSearch() {
  currentPage.value = 1
  // 移除 loadProjects() 调用，因为数据已经在内存中
}

// 分页处理
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
  // 移除 loadProjects() 调用，因为数据已经在内存中
}

function handleCurrentChange(val) {
  currentPage.value = val
  // 移除 loadProjects() 调用，因为数据已经在内存中
}

// 提交表单
async function handleSubmit() {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      const payload = { ...form.value }
      
      if (!form.value.id) {
        // 创建项目时自动生成GUID
        payload.id = generateGUID()
        await createProject(payload)
        
        // 创建用户项目关联
        if (form.value.project_manager) {
          const userProjectData = {
            Userid: form.value.project_manager,
            Porojectid: form.value.project_id,
            remark: `项目经理关联 - ${form.value.project_name}`
          }
          await createUserProject(userProjectData)
        }
        
        ElMessage.success('项目创建成功')
      } else {
        // 更新项目
        await updateProject(form.value.id, payload)
        
        // 检查项目经理是否变更
        if (form.value.project_manager !== originalProjectManager.value) {
          // 查找并更新用户项目关联
          const existingRelation = userProjectList.value.find(
            relation => relation.Porojectid === form.value.project_id
          )
          
          if (existingRelation) {
            // 更新现有关联
            const updateData = {
              Userid: form.value.project_manager,
              Porojectid: form.value.project_id,
              remark: `项目经理关联 - ${form.value.project_name}`
            }
            await updateUserProject(existingRelation.id, updateData)
          } else {
            // 创建新关联
            const userProjectData = {
              Userid: form.value.project_manager,
              Porojectid: form.value.project_id,
              remark: `项目经理关联 - ${form.value.project_name}`
            }
            await createUserProject(userProjectData)
          }
        }
        
        ElMessage.success('项目更新成功')
      }
      
      dialogVisible.value = false
      loadProjects()
      loadUserProjects() // 重新加载关联数据
    } catch (error) {
      ElMessage.error('操作失败，请重试')
      console.error('提交失败:', error)
    } finally {
      submitLoading.value = false
    }
  })
}

// 跳转到项目信息页面
function goToProjectInfo(project) {
  router.push(`/project/info/${project.id}`)
}

// 删除项目
function handleDelete(id) {
  ElMessageBox.confirm('确认删除该项目？此操作不可恢复', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 先查找项目信息
      const project = projectList.value.find(p => p.id === id)
      
      // 删除项目
      await deleteProject(id)
      
      // 删除相关的用户项目关联
      if (project) {
        const relations = userProjectList.value.filter(
          relation => relation.Porojectid === project.project_id
        )
        
        // 批量删除关联记录
        for (const relation of relations) {
          try {
            await deleteUserProject(relation.id)
          } catch (error) {
            console.error('删除用户项目关联失败:', error)
          }
        }
      }
      
      ElMessage.success('删除成功')
      loadProjects()
      loadUserProjects() // 重新加载关联数据
    } catch (error) {
      ElMessage.error('删除失败，请重试')
      console.error('删除失败:', error)
    }
  }).catch(() => {})
}

onMounted(() => {
  loadProjects()
  loadUsers()
  loadUserProjects()
})
</script>

<style scoped>
.project-list-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.project-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.title-section {
  flex: 1;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-icon {
  font-size: 24px;
  color: #67c23a;
}

.description {
  margin: 0;
  font-size: 14px;
  color: #909399;
  line-height: 1.5;
}

.create-btn {
  padding: 12px 20px;
  font-weight: 500;
  border-radius: 8px;
}

.search-section {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  flex: 1;
  max-width: 300px;
}

.project-table {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.project-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.project-icon {
  color: #67c23a;
  font-size: 16px;
}

.project-name {
  font-weight: 500;
  color: #303133;
}

.clickable {
  cursor: pointer;
  color: #409eff;
  text-decoration: none;
  transition: color 0.3s;
}

.clickable:hover {
  color: #66b1ff;
  text-decoration: underline;
}

.clickable {
  cursor: pointer;
  transition: color 0.3s ease;
}

.clickable:hover {
  color: #409eff;
  text-decoration: underline;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background: #f5f7fa !important;
  font-weight: 600;
}

:deep(.el-dialog) {
  border-radius: 12px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  padding: 20px 24px;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 16px 24px;
}

@media (max-width: 768px) {
  .project-list-container {
    padding: 10px;
  }
  
  .header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .search-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input {
    max-width: none;
  }
}
</style> 